package ws.very.translator

import scala.util.Try
import org.json4s.JArray
import org.json4s.JString
import org.json4s.JValue
import org.json4s.jvalue2extractable
import org.json4s.native.JsonMethods.parse
import org.json4s.string2JsonInput
import dispatch.as
import dispatch.enrichFuture
import dispatch.implyRequestHandlerTuple
import dispatch.url
import dispatch.Http
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods.compact
import org.json4s.native.JsonMethods.parse
import org.json4s.native.JsonMethods.render
import org.json4s.JsonAST.JObject
//FIXME:auto模式下有bing有些语言无法识别
//FIXME:We are not yet able to translate from Kinyarwanda into Vietnamese
case class BingTrans(appId: S)(implicit executor: scala.concurrent.ExecutionContext, http: Http) {
  def translate(txt: S, fromLang: S = "")(implicit toLang: S) = new {

    val resStr = http(
      url(
        //http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=%22TMnXvppgOs3x9MZIFaukrkPdyhp0bsr4H7sjdwFBXZvA*%22&texts=[%22i+am%22]&from=%22ja%22&to=%22zh-chs%22
        s"http://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=%22${appId}%22&from=%22${fromLang}%22&to=%22${toLang}s%22" //&texts=[%22i+am%22]
        ).addQueryParameter("texts", compact(render(txt.split("\r\n").toList))) OK as.String).either
    lazy val fixRes = resStr.right.map { _.substring(1) } //.right.map { _.replaceAll(",+", ",") }

    lazy val parseJson = fixRes.right.map { r =>
      Try { parse(r) }
    }
    lazy val json2Obj = (parseJson).right.map { t =>
      t.map { a =>
        extract(a)
      }
    } // 

    def extract(j: JValue) =
      j match {
        case JArray(a) =>
          a.map {
            case json: JObject =>
              (json \ "TranslatedText").extract[String] -> (json \ "From").extract[String]
          }
      }
    lazy val rs = json2Obj.right.map { t =>
      t.map { j =>
        val (txts, langs) = j.unzip
        txts.mkString("\r\n") -> langs.groupSelfCount.maxBy { _._2 }._1
      }
    }

  }
}